/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package rfid;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;

/**
 *
 * @author xandru
 */

public class RFIDBeeper implements  RFIDEventListener{

    byte[] buf;
    int MILISECONDS = 50;
    int HERTZIOS = 2000;
    AudioFormat af;
    SourceDataLine sdl;

    public RFIDBeeper() throws LineUnavailableException
    {
        buf = new byte[MILISECONDS*8];
        for (int i=0; i<buf.length; i++) 
        {
            double angle = i / (8000.0 / HERTZIOS) * 2.0 * Math.PI;
            buf[i] = (byte)(Math.sin(angle) * 80.0);
        }
        af = new AudioFormat(8000f,8,1,true,false);
        sdl = AudioSystem.getSourceDataLine(af);
    }

    public void setHertzios(int hz)
    {
        HERTZIOS = hz;
    }

     public void setMilisecons(int ms)
    {
        MILISECONDS = ms;
    }


    public void doBeep() throws LineUnavailableException
    {
        sdl.open(af);
        sdl.start();
        sdl.write(buf,0,buf.length);
        sdl.drain();
        sdl.close();
    }

    public void onNewTag(RFIDTagEvent e) {
        try {
            doBeep();
        } catch (LineUnavailableException ex) {
            System.out.println(ex.getMessage());
        }
    }

    public void onUpdateTag(RFIDTagEvent e) {
        try {
            doBeep();
        } catch (LineUnavailableException ex) {
            System.out.println(ex.getMessage());
        }
    }

}
